let qqMapSdk = require("../../utils/qqmap-wx-jssdk.js");
let util = require('../../utils/util.js')
const {
  imgConfig,
  config
} = require('../../utils/config.js')
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    signType: '', //0上班打卡 1下班打卡
    is_out: 2, //1办公地点打卡 2外勤打卡
    nowTime: '', //当前时间
    nowDate: '', //当前年月日
    nowDay: '', //星期几
    tip: '', //提示 上午好、下午好
    current_address: '', //当前定位地址
    status: 0, //0未打卡 1已打卡
    latlng: [], //经纬度
    nowTimeStop: '', //已打卡时间
    area: {}, //考勤点多个
    record: [], //打卡记录
  },


  onLoad: function (options) {
    console.log(options)
    this.getCurrentTime();
    this.setData({
      clockStu: options.status,
      nowTime: this.getTime(),
      nowDate: util.formatTime(new Date()),
      nowDay: util.formatDay(new Date()),
      tip: util.formatSole(),
    })
  },
  onReady(){
    this.setData({
        avatar: app.globalData.userInfo.photo, //头像
        stuName: app.globalData.userInfo.stuName, //姓名
        phoneNumber: app.globalData.userInfo.stuTel, //手机号
      })
  },
  onShow: function () {
    this.getLastClock()
    this.setData({
      status: 0,
      current_address: '',
    })
  },


  signTap() {
    var that = this;
    if (!that.data.current_address) {
      return wx.showToast({
        title: '未获取当前定位',
        icon: 'error'
      })
    }
    if (that.data.is_out != 1) {
      return wx.showToast({
        title: '未进入打卡范围',
        icon: 'error'
      })
    }
    that.punchTheClock()
    /*  var list = that.data.record.concat({
       'times': that.data.nowTime,
       'address': that.data.current_address
     });
     console.log(list)
     wx.vibrateLong(); //手机震动提示
     that.getSignRecord();
     that.setData({
       status: 1, //已打卡
       record: list,
       nowTimeStop: that.data.nowTime,
     })
     wx.showToast({
       title: '打卡成功',
       icon: 'none'
     }) */
  },
  /**
   * 打卡 发送请求
   */
  punchTheClock: function () {
    var that = this
    console.log(that.data.clockStu)
    if (that.data.clockStu == 0) {
      var content = '是否确认上课打卡?'
    } else {
      var content = '是否确认下课打卡?'
    }
    //打卡确认
    wx.showModal({
      title: '提示',
      content: content,
      success(res) {
        if (res.confirm) {
          if (that.data.clockStu == 0) {
            that.addClock()
          } else {
            that.updateClock()
          }
        } else if (res.cancel) {
          wx.showToast({
            title: '已取消打卡!',
            icon: 'none',
            duration: 1000
          })
        }
      }
    })

  },
  addClock() {
    var that = this
    var studentInfo = app.globalData.userInfo
    wx.request({
      url: `${config}/wechat/wxclock/saveClock`,
      method: 'post',
      data: {
        stuId: studentInfo.id,
        addDate: that.data.nowDate,
        addTime: that.data.nowTime,
        courseId: app.globalData.courseId,
        chapterId: app.globalData.chapterId,
        clockStatus: 0,
        addAddress: that.data.current_address
      },
      success(resp) {
        console.log(resp)
        //打卡状态
        if (resp.data.code == 0) {

          wx.vibrateLong(); //手机震动提示
          that.getSignRecord();
          that.setData({
            status: 1, //已打卡
            arriveTime: that.data.nowTime,
            arriveAddress: that.data.current_address,
            nowTimeStop: that.data.nowTime,
          })
          app.globalData.clockStatus = true
          wx.showToast({
            title: '打卡成功',
            duration: 1000
          })
          setTimeout(function () {
            wx.switchTab({
              url: '/pages/my/my',
            })
          }, 1000)
        }
      }
    }) //请求结束
  },
  updateClock() {
    var that = this
    var studentInfo = app.globalData.userInfo
    wx.request({
      url: `${config}/wechat/wxclock/saveClock`,
      method: 'post',
      data: {
        stuId: studentInfo.id,
        addDate: that.data.addDate,
        updateTime: that.data.nowTime,
        courseId: app.globalData.courseId,
        chapterId: app.globalData.chapterId,
        evaluate: app.globalData.evaluate,
        score: app.globalData.score,
        clockStatus: 1,
        updateAddress: that.data.current_address
      },
      success(resp) {
        console.log(resp)
        //打卡状态
        if (resp.data.code == 0) {
          wx.vibrateLong(); //手机震动提示
          that.getSignRecord();
          that.setData({
            status: 1, //已打卡
            leaveTime: that.data.nowTime,
            leaveAddress: that.data.current_address,
            nowTimeStop: that.data.nowTime,
          })
          app.globalData.clockStatus = false
          wx.showToast({
            title: '打卡成功',
            duration: 1000
          })
          setTimeout(function () {
            that.getLastClock()
            wx.switchTab({
              url: '/pages/my/my',
            })
          }, 1000)
        }
      }
    }) //请求结束
  },
  /**
   * 获取最新打卡参数
   */
  getLastClock() {
    var that = this
    var studentInfo = app.globalData.userInfo
    //globalData中存入新的打卡数据 用于返回后访问打卡页使用
    wx.request({
      url: `${config}/wechat/wxclock/getLastClock`,
      data: {
        stuId: app.globalData.userInfo.id
      },
      success(res) {
        if (res.data.clockEntity.addDate == that.data.nowDate) {
          that.setData({
            arriveAddress:res.data.clockEntity.addAddress,
            arriveTime:res.data.clockEntity.addTime,
            leaveAddress:res.data.clockEntity.updateAddress,
            leaveTime:res.data.clockEntity.updateTime
          })
        }else{
            return
        }
      }
    })
  },
  getCurrentTime: function () {
    var time = setInterval(() => {
      this.setData({
        nowTime: this.getTime()
      })
    }, 1000)
  },
  getTime() {
    let dateTime = '';
    let hh = new Date().getHours()
    let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() :
      new Date().getMinutes()
    let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() :
      new Date().getSeconds()
    dateTime = hh + ':' + mf + ':' + ss;
    return dateTime;
  },

  // 请求获取定位授权
  getUserAuth: function () {
    return new Promise((resolve, reject) => {
      wx.authorize({
        scope: 'scope.userLocation'
      }).then(() => {
        resolve()
      }).catch(() => {
        let that = this;
        wx.getSetting({
          success: (res) => {
            if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
              wx.showModal({
                title: '请求授权当前位置',
                content: '需要获取您的地理位置，请确认授权',
                success: function (res) {
                  if (res.cancel) {
                    wx.showToast({
                      title: '拒绝授权',
                      icon: 'none',
                      duration: 1000
                    })
                  } else if (res.confirm) {
                    wx.openSetting({
                      success: function (dataAu) {
                        if (dataAu.authSetting["scope.userLocation"] == true) {
                          //再次授权，调用wx.getLocation的API
                        } else {
                          wx.showToast({
                            title: '授权失败',
                            icon: 'none',
                            duration: 1000
                          })
                        }
                      }
                    })
                  }
                }
              })
            } else if (res.authSetting['scope.userLocation'] == undefined) {
            } else {
            }
          }
        })
      })
    })
  },

  getLocation: function () {
    const that = this
    // 实例化腾讯地图API核心类
    const QQMapWX = new qqMapSdk({
      key: 'VZGBZ-YIHCQ-SR55P-GNN73-DNDYF-CGF2O' // KEY必填
    });
    //获取当前位置
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        that.latitude = res.latitude
        that.longitude = res.longitude
        QQMapWX.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: function (res) {
            let address = res.result.formatted_addresses.recommend;
            that.getSignRecord();
            that.setData({
              current_address: address,
              latlng: [res.result.location.lat, res.result.location.lng]
            })
          },
          fail: function (res) {
            that.getUserAuth()
            wx.showToast({
              title: '获取定位失败，请打开手机定位，重新进入！',
              icon: 'none'
            });
          }
        })
      },
    })
  },
  // 刷新定位
  refreshAdd() {
    this.getSignRecord()
  },

  //处理打卡记录及判断打卡位置是否办公地点打卡
  getSignRecord: function () {
    var that = this;
    console.log(that.data.latlng);
    var distance = that.getDistance(that.data.latlng[0], that.data.latlng[1], 38.95223, 121.5255); //打卡地点经纬度
    console.log(distance)
    //判断距离  与打卡地点距离小于150米
    if (distance < 150) {
      that.setData({
        is_out: 1,
      })
    }
  },


  //经纬度距离计算
  getDistance: function (lat1, lng1, lat2, lng2, unit = false) {
    var radLat1 = lat1 * Math.PI / 180.0
    var radLat2 = lat2 * Math.PI / 180.0
    var a = radLat1 - radLat2
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
      Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)))
    s = s * 6378.137 // EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000 //输出为公里
    if (0) { //是否返回带单位
      if (s < 1) { //如果距离小于1km返回m
        s = s.toFixed(3)
        s = s * 1000 + "m"
      } else {
        s = s.toFixed(2)
        s = s + "km"
      }
    } else {
      s = s.toFixed(3)
      s = s * 1000
    }
    return s
  },



})